package com.travel.sso.controller;

import com.travel.common.util.CookieUtils;
import com.travel.common.util.JsonUtil;
import com.travel.common.util.TravelResult;
import com.travel.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class UserController {
    @Value("${TOKEN_KEY}")
    private String TOKEN_KEY;
    @Autowired
    private UserService userService;

    @RequestMapping("login.html")
    @ResponseBody
    public String login(String email, String password, String callback, HttpServletResponse response,
                        HttpServletRequest request) {
        TravelResult result = userService.doLogin(email, password);
        if (result.getStatus()) {//如果登录成功
            //将票据写入cookie
            CookieUtils.setCookie(request, response, TOKEN_KEY, result.getData().toString());
        }
        //callback是页面上指定的回调参数，用于jsonp请求
        return callback + "(" + JsonUtil.getJSON(result) + ")";
    }

    @RequestMapping("regist.html")
    @ResponseBody
    public String regist(String email, String password, String repwd, String callback, HttpServletResponse response,
                         HttpServletRequest request) {
        TravelResult result = userService.doRegist(email, password);
        if (result.getStatus()) {
            CookieUtils.setCookie(request, response, TOKEN_KEY, result.getData().toString());
        }
        return callback + "(" + JsonUtil.getJSON(result) + ")";
    }

    @RequestMapping("info.html")
    @ResponseBody
    public String check(String callback, HttpServletRequest request) {
        //从cookie中获取票据
        String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
        //查询用户信息
        TravelResult result = userService.getUserByToken(token);
        return callback + "(" + JsonUtil.getJSON(result) + ")";
    }

    @RequestMapping("logout.html")
    @ResponseBody
    public String logout(String callback, HttpServletRequest request) {
        String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
        TravelResult result = userService.doLogout(token);
        return callback + "(" + JsonUtil.getJSON(result) + ")";
    }

}
